package com.sangsang.kafka.serializer;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.sangsang.kafka.util.DateUtils;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.util.Optional;

/**
 * Date类型的反序列化
 *
 * @author liutangqi
 * @date 2025/1/21 9:18
 */
public class DateDeserializer {


    /**
     * Integer 转 LocalDateTime
     * 将距1970-01-01 00:00:00多少天的时间进行格式转换
     *
     * @author liutangqi
     * @date 2025/1/21 11:07
     * @Param
     **/
    public static class Integer2LocalDate implements ObjectDeserializer {
        @Override
        public LocalDate deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
            JSONObject jsonObject = JSONObject.parseObject(parser.getInput());
            Object fieldValue = getIgnoreCamel(jsonObject, fieldName);
            if (fieldValue == null) {
                return null;
            }
            return DateUtils.parseDate((Integer) fieldValue);
        }

        @Override
        public int getFastMatchToken() {
            return 0;
        }
    }

    /**
     * 获取值忽略驼峰
     *
     * @author liutangqi
     * @date 2025/1/21 10:45
     * @Param [jsonObject, fieldName]
     **/
    private static Object getIgnoreCamel(JSONObject jsonObject, Object fieldName) {
        //先看这个字段能不能找到
        if (jsonObject.containsKey(fieldName)) {
            return jsonObject.get(fieldName);
        }
        //找不到，进行驼峰转下划线
        return Optional.ofNullable(fieldName)
                .map(Object::toString)
                .map(StrUtil::toUnderlineCase)
                .map(m -> jsonObject.get(m))
                .orElse(null);
    }
}
